import React from 'react';
import {
  Space,
  Typography,
  Loading,
  Alert,
  Card,
  Button,
} from 'tdesign-react';
import { AddIcon } from 'tdesign-icons-react';
import type { Todo } from '../../types/todo.types';
import { TodoItem } from './TodoItem';

interface TodoListProps {
  todos: Todo[];
  onComplete: (id: number) => void;
  onRemove: (id: number) => void;
  isLoading?: boolean;
  error?: Error | null;
  updatingId?: number | null;
  onAddClick?: () => void;
}

export const TodoList: React.FC<TodoListProps> = ({
  todos,
  onComplete,
  onRemove,
  isLoading,
  error,
  updatingId,
  onAddClick,
}) => {
  if (isLoading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', padding: '64px 0' }}>
        <Loading size="large" />
      </div>
    );
  }

  if (error) {
    return (
      <Alert theme="error" message={`Error loading todos: ${error.message}`} style={{ marginBottom: '16px' }} />
    );
  }

  if (todos.length === 0) {
    return (
      <Card style={{ padding: '48px', textAlign: 'center', backgroundColor: '#f5f5f5' }}>
        <Typography.Title level="h6" style={{ color: '#666', marginBottom: '8px' }}>
          No todos yet
        </Typography.Title>
        <Typography.Text style={{ color: '#666', marginBottom: '24px', display: 'block' }}>
          Create your first todo to get started
        </Typography.Text>
        {onAddClick && (
          <Button
            theme="primary"
            icon={<AddIcon />}
            onClick={onAddClick}
          >
            Add Your First Todo
          </Button>
        )}
      </Card>
    );
  }

  const completedCount = todos.filter((todo) => todo.completed).length;
  const activeCount = todos.length - completedCount;

  return (
    <Space direction="vertical" size="large" style={{ width: '100%' }}>
      <Typography.Title level="h6" style={{ marginBottom: '16px' }}>
        Your Todos
      </Typography.Title>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
        <Typography.Text style={{ color: '#666' }}>
          {activeCount} active, {completedCount} completed
        </Typography.Text>
      </div>

      {todos.map((todo) => (
        <TodoItem
          key={todo.id}
          todo={todo}
          onComplete={onComplete}
          onRemove={onRemove}
          isUpdating={updatingId === todo.id}
        />
      ))}
    </Space>
  );
};